<template>
  <div class="assistant">
    <h1 class="page-title">AI学习助手</h1>
    
    <!-- 对话区域 -->
    <div class="chat-container">
      <!-- 消息记录 -->
      <div class="message-list" ref="messageList">
        <!-- 欢迎消息 -->
        <div class="message assistant-message">
          <div class="message-avatar">
            <el-avatar :size="40" icon="el-icon-user-solid" />
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <p>你好！我是你的AI学习助手。请告诉我你需要帮助的学科和问题，我会尽力帮助你解决。</p>
            </div>
            <div class="message-time">{{ formatTime(new Date()) }}</div>
          </div>
        </div>
        
        <!-- 消息列表 -->
        <div 
          v-for="(msg, index) in messages" 
          :key="index" 
          :class="['message', msg.role === 'user' ? 'user-message' : 'assistant-message']"
        >
          <div class="message-avatar">
            <el-avatar 
              :size="40" 
              :icon="msg.role === 'user' ? 'el-icon-user' : 'el-icon-user-solid'" 
            />
          </div>
          <div class="message-content">
            <div class="message-bubble" v-html="formatMessage(msg.content)"></div>
            <div class="message-time">{{ formatTime(msg.time) }}</div>
          </div>
        </div>
        
        <!-- 加载指示器 -->
        <div v-if="loading" class="loading-indicator">
          <div class="dot-flashing"></div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="input-area">
        <div class="subject-selector">
          <el-select v-model="selectedSubject" placeholder="选择学科" size="small">
            <el-option
              v-for="subject in subjects"
              :key="subject.id"
              :label="subject.name"
              :value="subject.name">
            </el-option>
          </el-select>
        </div>
        
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          placeholder="请输入你的问题..."
          resize="none"
          @keydown.enter.prevent="sendMessage"
        ></el-input>
        
        <div class="action-buttons">
          <el-button @click="clearMessages">清空对话</el-button>
          <el-button type="primary" @click="sendMessage" :disabled="loading || !userInput.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 常见问题区域 -->
    <div class="faq-section">
      <h2>常见问题示例</h2>
      <div class="faq-items">
        <div 
          v-for="(faq, index) in faqs" 
          :key="index"
          class="faq-item"
          @click="useQuestion(faq.question)"
        >
          <div class="faq-question">{{ faq.question }}</div>
          <div class="faq-subject">{{ faq.subject }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import DOMPurify from 'dompurify';

// 学科列表
const subjects = ref([
  { id: 1, name: '语文' },
  { id: 2, name: '数学' },
  { id: 3, name: '英语' },
  { id: 4, name: '物理' },
  { id: 5, name: '化学' },
  { id: 6, name: '生物' },
]);

// 常见问题示例
const faqs = ref([
  { question: '二次函数的最值怎么求？', subject: '数学' },
  { question: '牛顿第二定律的应用有哪些？', subject: '物理' },
  { question: '如何理解并列句和复合句的区别？', subject: '语文' },
  { question: '英语中的现在完成时态用法是什么？', subject: '英语' },
  { question: '元素周期表的排列规律是什么？', subject: '化学' },
  { question: '光合作用的过程和条件是什么？', subject: '生物' }
]);

const messageList = ref(null);
const userInput = ref('');
const selectedSubject = ref('');
const messages = ref([]);
const loading = ref(false);

// 加载历史记录
const loadHistory = async () => {
  try {
    const response = await axios.get('/api/student/history/assistant', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data && Array.isArray(response.data)) {
      // 将历史记录转换为消息格式
      const historyMessages = response.data.map(record => [
        {
          role: 'user',
          content: record.question,
          time: new Date(record.time)
        },
        {
          role: 'assistant',
          content: record.answer,
          time: new Date(record.time)
        }
      ]).flat();
      
      messages.value = historyMessages;
    }
  } catch (error) {
    console.error('加载历史记录失败:', error);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return;
  
  if (!selectedSubject.value) {
    ElMessage.warning('请先选择学科');
    return;
  }
  
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: userInput.value,
    time: new Date()
  };
  messages.value.push(userMessage);
  
  // 清空输入框并滚动到底部
  const inputText = userInput.value;
  userInput.value = '';
  await scrollToBottom();
  
  // 显示加载状态
  loading.value = true;
  
  try {
    console.log('开始收集学生数据...');
    
    // 准备学习数据对象
    const learningDataSummary = {
      subject: selectedSubject.value,
      question: inputText,
      studentPerformance: {
        averageScore: null,
        completedExercises: 0,
        studyTime: 0,
        mistakeCount: 0,
        recentPractices: []
      }
    };
    
    // 尝试获取学生的学习进度数据
    try {
      const studentDataResponse = await axios.get('/api/student/learning-progress', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (studentDataResponse.data) {
        console.log('获取到学习进度数据:', studentDataResponse.data);
        
        // 提取相关科目数据
        const subjectData = (studentDataResponse.data.subjects || [])
          .find(s => s.name === selectedSubject.value);
        
        if (subjectData) {
          console.log('找到科目数据:', subjectData);
          // 添加科目进度数据
          learningDataSummary.studentPerformance.progress = subjectData.progress;
        }
        
        // 提取其他学习数据
        const recentPractice = studentDataResponse.data.recentPractice || {};
        if (recentPractice) {
          console.log('获取到最近练习数据:', recentPractice);
          learningDataSummary.studentPerformance.completedExercises = 
            recentPractice.totalSessions || 0;
          learningDataSummary.studentPerformance.studyTime = 
            recentPractice.totalTime || 0;
        }
      }
    } catch (error) {
      console.warn('获取学习进度数据失败:', error);
    }
    
    // 尝试获取错题本数据
    try {
      const mistakesResponse = await axios.get(`/api/student/mistake-collection`, {
        params: {
          subject: selectedSubject.value
        },
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (mistakesResponse.data && Array.isArray(mistakesResponse.data)) {
        console.log('获取到错题本数据:', mistakesResponse.data.length, '条记录');
        learningDataSummary.studentPerformance.mistakeCount = mistakesResponse.data.length;
        
        // 提取最近的错题作为练习记录
        const recentMistakes = mistakesResponse.data
          .slice(0, 5)
          .map(mistake => ({
            date: mistake.createdTime || '未知日期',
            topic: mistake.knowledgePoint || '未知知识点',
            score: mistake.isCorrect ? '正确' : '错误'
          }));
        
        // 添加到练习记录中
        if (recentMistakes.length > 0) {
          learningDataSummary.studentPerformance.recentPractices = recentMistakes;
          console.log('添加错题记录到练习数据:', recentMistakes);
        }
      }
    } catch (error) {
      console.warn('获取错题本数据失败:', error);
    }
    
    console.log('发送到AI的完整学生学习数据:', learningDataSummary);
    
    // 发送请求到后端，并附带学生数据
    const response = await axios.post('/api/student/ai-assistant', learningDataSummary, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    // 添加助手回复
    if (response.data && response.data.analysis) {
      const assistantMessage = {
        role: 'assistant',
        content: response.data.analysis,
        time: new Date()
      };
      messages.value.push(assistantMessage);
      
      // 保存到历史记录
      try {
        await axios.post('/api/student/history/assistant', {
          subject: selectedSubject.value,
          question: inputText,
          answer: response.data.analysis,
          time: new Date()
        }, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
      } catch (error) {
        console.error('保存历史记录失败:', error);
      }
    } else {
      throw new Error('未收到有效回复');
    }
  } catch (error) {
    console.error('AI助手请求失败:', error);
    messages.value.push({
      role: 'assistant',
      content: '抱歉，我遇到了一些问题，无法回答你的问题。请稍后再试。',
      time: new Date()
    });
  } finally {
    loading.value = false;
    await scrollToBottom();
  }
};

// 清空对话
const clearMessages = () => {
  messages.value = [];
};

// 使用示例问题
const useQuestion = (question) => {
  userInput.value = question;
  
  // 根据问题自动选择学科
  const matchedFaq = faqs.value.find(faq => faq.question === question);
  if (matchedFaq) {
    selectedSubject.value = matchedFaq.subject;
  }
};

// 格式化时间
const formatTime = (date) => {
  return new Date(date).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 格式化消息内容（支持简单的Markdown转HTML）
const formatMessage = (content) => {
  if (!content) return '';
  
  // 一个简单的函数来处理基本的Markdown格式
  let html = content
    // 处理标题
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    // 处理粗体和斜体
    .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/gim, '<em>$1</em>')
    // 处理代码块
    .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
    // 处理行内代码
    .replace(/`(.*?)`/gim, '<code>$1</code>')
    // 处理链接
    .replace(/\[(.*?)\]\((.*?)\)/gim, '<a href="$2" target="_blank">$1</a>')
    // 处理无序列表
    .replace(/^\- (.*$)/gim, '<ul><li>$1</li></ul>')
    // 处理段落
    .replace(/\n/gim, '<br>');
  
  // 合并相邻的<ul>标签
  html = html.replace(/<\/ul><ul>/gim, '');
  
  // 安全过滤
  return DOMPurify.sanitize(html);
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight;
  }
};

// 监听消息变化，自动滚动
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

onMounted(() => {
  // 如果URL中有学科参数，自动选择
  const urlParams = new URLSearchParams(window.location.search);
  const subjectParam = urlParams.get('subject');
  
  if (subjectParam) {
    const subject = subjects.value.find(s => s.name === subjectParam);
    if (subject) {
      selectedSubject.value = subject.name;
    }
  }
  
  // 加载历史记录
  loadHistory();
  
  // 初始化滚动到底部
  scrollToBottom();
});
</script>

<style scoped>
.assistant {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 500px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.message-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  word-break: break-word;
}

.user-message .message-bubble {
  background-color: #1a73e8;
  color: white;
}

.assistant-message .message-bubble {
  background-color: white;
}

.message-time {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.input-area {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: white;
}

.subject-selector {
  margin-bottom: 10px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

.faq-section {
  margin-top: 20px;
}

.faq-section h2 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.faq-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.faq-item {
  padding: 12px 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.faq-item:hover {
  background-color: #f0f7ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.faq-question {
  font-weight: 500;
  margin-bottom: 5px;
}

.faq-subject {
  font-size: 12px;
  color: #909399;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  margin: 10px 0;
}

.dot-flashing {
  position: relative;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #1a73e8;
  color: #1a73e8;
  animation: dot-flashing 1s infinite linear alternate;
  animation-delay: 0.5s;
}

.dot-flashing::before, .dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
}

.dot-flashing::before {
  left: -15px;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #1a73e8;
  color: #1a73e8;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 15px;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #1a73e8;
  color: #1a73e8;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dot-flashing {
  0% {
    background-color: #1a73e8;
  }
  50%, 100% {
    background-color: rgba(26, 115, 232, 0.2);
  }
}

@media (max-width: 768px) {
  .faq-items {
    grid-template-columns: 1fr;
  }
  
  .message-content {
    max-width: 85%;
  }
}
</style> 